/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.net.httpserver.Headers;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javaapplication5.controller.AddressBookController;
import javaapplication5.model.Contact;
import javaapplication5.model.ContactsTable;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author mathieubakrim
 */
public class AddressBookView extends JFrame{
    
    // DECLARATIONS
        
    // labels & textfields & buttons & Jcombobox
    private String[] tab_string = {"lastName", "firstName", "phoneNumber", "addressPro", 
        "addressPer", "homePage", "emailPro", "emailPer", "group"};            
    
    private JTextField jtfFilter;
    private JTextField[] tab_textField = new JTextField[tab_string.length];
    
    private JLabel[] tab_label = new JLabel[tab_string.length];
    private JLabel jlbFilter = new JLabel();
    private JLabel jlbGroup = new JLabel("Group");    
    private JLabel[] tab_labelProfile = new JLabel[tab_string.length];
    
    private TitledBorder formBorder,
                         listBorder,
                         profileBorder;
    
    
    private JButton ok = new JButton("OK"),
                    cancel = new JButton ("Cancel"),
                    previous = new JButton ("Go back"),
                    delete = new JButton("Delete the line");
    
    protected JComboBox jcbGroup = new JComboBox();
    protected JComboBox jcbGroupList = new JComboBox();
    
    // menu
    private JMenuBar menuBar = new JMenuBar();
    private JMenu file = new JMenu("File");
    private JMenu services = new JMenu("Services");
    private JMenu help = new JMenu("Help");
    
    private JMenuItem quit = new JMenuItem("Quit");
    private JMenuItem createContact = new JMenuItem("Create a contact");
    private JMenuItem contactList = new JMenuItem("Contact list");
    private JMenuItem credits = new JMenuItem("Credits");
    // end menu
    
    private  JPanel thePanel = new JPanel(),
       theListPanel = new JPanel(),
       theFilterPanel = new JPanel(),
       theFormPanel = new JPanel(),
       theProfilePanel = new JPanel();
    
    protected AddressBookController controller ;

    
    // list & JTable
    protected ContactsTable contactsTable;
    private ArrayList<Contact> contacts;
    private JTable jtContacstList;
    private JScrollPane listSPane;
    private TableRowSorter<TableModel> sorter;
    
    //CONSTRUCTOR
    public AddressBookView(AddressBookController controller){
        this.controller = controller;
        this.contacts = controller.getContactsList();
        // SETS UP THE VIEW
        this.setTitle("Address Book Application");
        this.setSize(1024, 768);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        
        this.setContentPane(thePanel);
        thePanel.setLayout(new GridBagLayout());
        
         for(int i = 0; i < tab_string.length; i++){
            tab_label[i] = new JLabel(tab_string[i]);
         }
        initList();
        initForm();
        initProfile();
        initMenu();

        // xPos, yPos, xWeight, yWeight
        addComp(thePanel, theListPanel, 0, 1, 4, 4, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE);        
        addComp(thePanel, theFormPanel,    1, 1, 2, 1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE);
        addComp(thePanel, theProfilePanel, 1, 2, 2, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
       
    }
    
    private void initMenu(){
        // INIT
        file.addSeparator();
        file.add(quit);
        services.add(createContact);
        services.add(contactList);
        help.add(credits);
        
        // ADD TO LISTENERS
        quit.addActionListener(new QuitListener());
        createContact.addActionListener(new CreateContactListener());
        contactList.addActionListener(new AlphaListListener());
        //TODO : credits
        
        // CREATE
        menuBar.add(file);
        menuBar.add(services);
        menuBar.add(help);
        setJMenuBar(menuBar);
        

        
    }
    
    private void initForm(){
        
        theFormPanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 5, 5));
        theFormPanel.setLayout(new GridLayout(10,2,5,5));
        //theFormPanel.setBackground(Color.yellow);
                
        formBorder = BorderFactory.createTitledBorder("Create a contact");
        formBorder.setTitleJustification(TitledBorder.CENTER);
        theFormPanel.setBorder(formBorder);
        
        
        for(int i = 0; i < tab_string.length -1; i++){             
            theFormPanel.add(new JLabel(tab_string[i]));
            tab_textField[i] = new JTextField();
            theFormPanel.add(tab_textField[i]);
        }
        for (int i = 0; i < controller.getGroup().length; i++) {
            jcbGroup.addItem(controller.getGroup()[i]);       
        }
        theFormPanel.add(jlbGroup);
        theFormPanel.add(jcbGroup);
        
        
        // ADD TO PANEL & LISTENERS
        theFormPanel.add(ok);
        ok.addActionListener(new CreateContactListener());

        System.out.println("init form ok");

    }
    
    private void initProfile() {
        theProfilePanel.setBorder(BorderFactory.createEmptyBorder(9, 2, 5, 5));
        theProfilePanel.setLayout(new GridLayout(9,2,5,5));
        //theProfilePanel.setBackground(Color.yellow);
        
        profileBorder = BorderFactory.createTitledBorder("Contact profile");
        profileBorder.setTitleJustification(TitledBorder.CENTER);
        theProfilePanel.setBorder(profileBorder);
        
        for(int i = 0; i < tab_string.length; i++){
            theProfilePanel.add(tab_label[i]);
            tab_labelProfile[i] = new JLabel(" - ");
            theProfilePanel.add(tab_labelProfile[i]);
        }
        System.out.println("init profile ok");
    }
    
    private void initList(){
        theListPanel.setLayout(new BorderLayout());
        listBorder = BorderFactory.createTitledBorder("Your contact list");
        listBorder.setTitleJustification(TitledBorder.CENTER);
        theListPanel.setBorder(listBorder);
        
        contactsTable = controller.createContactTable(tab_string, contacts);        
        jtContacstList = new JTable (contactsTable);
        jcbGroupList.equals(jcbGroup);
        
        
        // Group combobox
        for (int i = 0; i < controller.getGroup().length; i++) {
            jcbGroupList.addItem(controller.getGroup()[i]);       
        }
        TableColumn groupColumn = jtContacstList.getColumnModel().getColumn(8);
        groupColumn.setCellEditor(new DefaultCellEditor(jcbGroupList));
        
        // Sorter
        jtContacstList.setAutoCreateRowSorter(true);
        SelectionListener listener = new SelectionListener(jtContacstList);
        ListSelectionModel listSelectionModel = jtContacstList.getSelectionModel();
        listSelectionModel.addListSelectionListener(listener);
        
        // Filter   
        JPanel jpFilter = new JPanel();                             
        jpFilter.add(new JButton(new FilterAction()), BorderLayout.EAST);
        jpFilter.add(new JButton(new GroupFilterAction()), BorderLayout.WEST);
        jpFilter.add(new JButton(new ClearFilterAction()), BorderLayout.CENTER);
        
        sorter = new TableRowSorter<TableModel>(jtContacstList.getModel());
        jtContacstList.setRowSorter(sorter);
        
        listSPane = new JScrollPane(jtContacstList);
        listSPane.setPreferredSize(new Dimension(700, 500));
        jtContacstList.setFillsViewportHeight(true);
        
        theListPanel.add(listSPane, BorderLayout.NORTH);
        theListPanel.add(jpFilter, BorderLayout.SOUTH);
        theListPanel.add(delete, BorderLayout.CENTER);
        delete.addActionListener(new DeleteListener());
        
        System.out.println("init list ok");      
    }
         
    
    // SETS THE RULES FOR A COMPONENT DESTINED FOR A GRIDBAGLAYOUT & ADDS IT
    private void addComp(JPanel thePanel, JComponent comp, int xPos, int yPos,
            int compWidth, int compHeight, int place, int stretch){
        
        GridBagConstraints gridConstraints = new GridBagConstraints();
        
        gridConstraints.gridx = xPos;
        gridConstraints.gridy = yPos;
        gridConstraints.gridwidth = compWidth;
        gridConstraints.gridheight = compHeight;
        gridConstraints.weightx = 100;
        gridConstraints.weighty = 100;
        gridConstraints.insets = new Insets(5, 5, 5, 5);
        gridConstraints.anchor = place;
        gridConstraints.fill = stretch;
        
        thePanel.add(comp, gridConstraints);
    }

    
    
    // INNER CLASSES FOR LISTENERS
       
    class QuitListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Have a nice day :)");
            System.exit(0);
        }
    }


    class AlphaListListener implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JOptionPane.showMessageDialog(null, "You will have your alphabetical contacts list soon");
            //controller.showAlphaList();
        }
        //
    }
     class CreateContactListener implements ActionListener{
        public void actionPerformed(ActionEvent e){     
            contactsTable.addContact(controller.createContact(tab_textField, jcbGroup.getSelectedItem().toString())); 
            JOptionPane.showMessageDialog(null, "Person Saved");

            // Set the profile values with the new contact
            for(int i = 0; i < tab_string.length-1; i++)                                         
                tab_labelProfile[i].setText(tab_textField[i].getText());
            int tmp = tab_labelProfile.length-1;
            tab_labelProfile[tmp].setText(jcbGroup.getSelectedItem().toString());

            // Set Textfield text to null
            for(int i=0; i<tab_textField.length-1;i++)
                tab_textField[i].setText("");  
            
        controller.updateData(contactsTable.getContacts());
             
        }
    }
    
    class DeleteListener extends AbstractAction{

        public DeleteListener() {
            super("Delete");
        }
        
        // Delete a row, even if it position has changed after a sort.
        public void actionPerformed(ActionEvent e){
                int[] selection = jtContacstList.getSelectedRows();
                int[] modelIndexes = new int[selection.length];
                for(int i = selection.length -1; i>= 0; i--){
                    modelIndexes[i] = jtContacstList.getRowSorter().convertRowIndexToModel(selection[i]);                    
                }
                
                Arrays.sort(modelIndexes);
                for(int i = modelIndexes.length -1; i>= 0; i--){
                    contactsTable.removeContact(modelIndexes[i]);
                }            
        controller.updateData();
        }
        
        
    }
    
    class SelectionListener implements ListSelectionListener {
        JTable table;
        private SelectionListener(JTable jtContacstList) {
            this.table = jtContacstList;
        }
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting())
                return;
            ListSelectionModel lsm = (ListSelectionModel)e.getSource();
            if (lsm.isSelectionEmpty()) {
                 System.out.println("No rows selected");
            }
             else{
                 int selectedRow = lsm.getMinSelectionIndex();                 
                 for(int j = 0; j<table.getColumnCount()-1; j++){
                        System.out.println("GetValue at: " + table.getValueAt(selectedRow, j));
                        tab_labelProfile[j].setText(table.getValueAt(selectedRow, j).toString());
                 }
                 int tmp = tab_labelProfile.length-1;
                 tab_labelProfile[tmp].setText(table.getValueAt(selectedRow, tmp).toString());
                 controller.updateData();
            }
        }
       
    }
    
    
    class FilterAction extends AbstractAction{
        private FilterAction(){
            super("Filter");
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
            String regex = JOptionPane.showInputDialog("Regex de filtre : ");
            sorter.setRowFilter(RowFilter.regexFilter(regex, 0, 1));
        }
    }
    
    class GroupFilterAction extends AbstractAction{
        private GroupFilterAction(){
            super("Group filtering");
        }
        public void actionPerformed(ActionEvent ae) {
            String[] groups = controller.getGroup();
            
            String regex = (String)JOptionPane.showInputDialog(null, "Group:", "Which group",
                    JOptionPane.QUESTION_MESSAGE, null, groups, groups[0]);
            sorter.setRowFilter(RowFilter.regexFilter(regex));
        }
    }
    class ClearFilterAction extends AbstractAction{
        private ClearFilterAction(){
            super("Clear Filter");
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
            String regex = "";
            sorter.setRowFilter(RowFilter.regexFilter(regex));
        }
    }
    
    class HyperLinkAction implements MouseListener{
        private String url = null;
        private String anchor = null;
        @Override
        public void mouseClicked(MouseEvent me) {
            
        }

        @Override
        public void mousePressed(MouseEvent me) {
            
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseEntered(MouseEvent me) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseExited(MouseEvent me) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        
    }
}
